"use client";

import { useState } from "react";
import { Button, Modal, Input, QRCode, Space, App } from "antd";
import { ShareAltOutlined, CopyOutlined, QrcodeOutlined } from "@ant-design/icons";
import { api } from "~/trpc/react";
import type { Course } from "@prisma/client";

interface CourseShareButtonProps {
  course: Course;
}

export function CourseShareButton({ course }: CourseShareButtonProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [inviteLink, setInviteLink] = useState("");
  const { message } = App.useApp();

  const generateInviteMutation = api.courses.generateInviteLink.useMutation({
    onSuccess: (invitation) => {
      // 生成邀请链接
      const link = `${window.location.origin}/courses/join/invitation/${invitation.id}`;
      setInviteLink(link);
    },
    onError: (error) => {
      void message.error(error.message || "生成邀请链接失败");
    },
  });

  const handleShare = async () => {
    try {
      setIsModalOpen(true);
      if (!inviteLink) {
        const invitation = await generateInviteMutation.mutateAsync({ courseId: course.id });
        const link = `${window.location.origin}/courses/join/invitation/${invitation.id}`;
        setInviteLink(link);
      }
    } catch (error) {
      console.error("生成邀请链接时出错:", error);
    }
  };

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(inviteLink);
      void message.success("邀请链接已复制到剪贴板");
    } catch (error) {
      void message.error("复制失败，请手动复制");
    }
  };

  return (
    <App>
      <Button
        icon={<ShareAltOutlined />}
        onClick={handleShare}
        loading={generateInviteMutation.isLoading}
      >
        分享课程
      </Button>

      <Modal
        title="分享课程"
        open={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
        footer={null}
      >
        <div className="space-y-6 py-4">
          <div>
            <h4 className="mb-2 font-medium">课程名称</h4>
            <p>{course.title}</p>
          </div>

          <div>
            <h4 className="mb-2 font-medium">邀请链接</h4>
            <Space.Compact style={{ width: "100%" }}>
              <Input value={inviteLink} readOnly />
              <Button icon={<CopyOutlined />} onClick={handleCopy}>
                复制
              </Button>
            </Space.Compact>
          </div>

          <div>
            <h4 className="mb-2 font-medium">二维码</h4>
            <div className="flex justify-center">
              <QRCode value={inviteLink || "-"} />
            </div>
          </div>

          <div className="text-gray-500 text-sm">
            <p>* 邀请链接7天内有效</p>
            <p>* 学生可以通过链接直接加入课程</p>
          </div>
        </div>
      </Modal>
    </App>
  );
}